package org.BooCrack.bookstore.pay.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.BooCrack.bookstore.common.pojo.BSResult;
import org.BooCrack.bookstore.common.utils.Response;
import org.BooCrack.bookstore.common.utils.ResponseResult;
import org.BooCrack.bookstore.exception.BSException;
import org.BooCrack.bookstore.model.entity.BookInfo;
import org.BooCrack.bookstore.model.entity.custom.Cart;
import org.BooCrack.bookstore.model.entity.User;
import org.BooCrack.bookstore.model.entity.custom.OrderCustom;
import org.BooCrack.bookstore.model.service.IBookInfoService;
import org.BooCrack.bookstore.model.service.ICartService;
import org.BooCrack.bookstore.model.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
//@RequestMapping("/order")
@RequestMapping("/user/V3")
@Api(value = "v1", tags = "3.BooCrack书城订单接口")
public class OrderController {


    @Autowired
    private IOrderService orderService;

    @Autowired
    private ICartService cartService;

    @Autowired
    private IBookInfoService bookInfoService;

    /**
     * 填写订单信息页面
     *
     * @param bookId
     * @param buyNum
     * @param request
     * @return
     */
    @GetMapping("/order/info")
    @ApiOperation(value = "填写订单信息页面", notes = "填写订单信息页面")
    public ResponseResult orderInfo(@RequestParam(required = false, defaultValue = "0") int bookId,
                                    @RequestParam(required = false, defaultValue = "0") int buyNum,
                                    HttpServletRequest request) throws BSException {

        if (bookId != 0) {
            //点了立即购买，放到request域中，也session的立即购买域中以区分购物车中的书籍
            BookInfo bookInfo = bookInfoService.findById(bookId);
            if (bookInfo != null) {
                BSResult bsResult = cartService.addToCart(bookInfo, null, buyNum);
                request.getSession().setAttribute("buyNowCart", bsResult.getData());
                request.setAttribute("cart", bsResult.getData());
                return Response.createOkResp("order_info",bsResult.getData()) ;
            } else {
                request.setAttribute("exception", "不好意思，书籍库存不足或不存在了！");
                return Response.createFailResp("exception"+"不好意思，书籍库存不足或不存在了！");
            }
        }
        //没有点立即购买，购物车中的总金额大于0才让填写订单信息
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        if (cart != null && cart.getTotal() > 0) {
            return Response.createFailResp("order_info");
        } else {
            return Response.createFailResp("cart"+"没有点任何商品");
        }


    }

    @GetMapping("/order/{orderId}")
    @ApiOperation(value = "根据id查看订单详情", notes = "根据id查看订单详情")
    public ResponseResult toPay(@PathVariable("orderId") String orderId, Model model) {

        BSResult bsResult = orderService.findOrderById(orderId);

        if (bsResult.getCode() == 200) {
            model.addAttribute("order", bsResult.getData());
            return Response.createOkResp("payment",bsResult.getData());
        }
        return Response.createFailResp("exception");
    }

    @DeleteMapping("/order/{orderId}")
    @ApiOperation(value = "根据id删除订单", notes = "根据id删除订单")
    public ResponseResult deletion(@PathVariable("orderId") String orderId) {

        BSResult bsResult = orderService.deleteOrder(orderId);

        if (bsResult.getCode() == 200) {
            //return "redirect:/order/list";
            return Response.createOkResp();
        }
        //return "exception";
        return Response.createFailResp("exception");
    }

    /**
     * 订单列表
     *
     * @return
     */
    @GetMapping("/order")
    @ApiOperation(value = "订单列表", notes = "订单列表")
    public ResponseResult orderList(HttpServletRequest request) {

        User loginUser = (User) request.getSession().getAttribute("loginUser");

        List<OrderCustom> orderCustoms = orderService.findOrdersByUserId(loginUser.getUserId());

        request.setAttribute("orderCustoms", orderCustoms);

        //return "order_list";
        return Response.createOkResp(orderCustoms);
    }

    /**
     * 创建订单
     *
     * @return
     */
    @PostMapping("/order")
    @ApiOperation(value = "新增订单", notes = "新增订单")
    public ResponseResult createOrder(User userDTO, String express, int payMethod, HttpServletRequest request) {

        //立即购买,优先创建订单
        Cart buyNowCart = (Cart) request.getSession().getAttribute("buyNowCart");

        User loginUser = (User) request.getSession().getAttribute("loginUser");
        userDTO.setUserId(loginUser.getUserId());
        userDTO.setZipCode(loginUser.getZipCode());

        if (buyNowCart != null) {
            BSResult bsResult = orderService.createOrder(buyNowCart, userDTO, express, payMethod);

            if (bsResult.getCode() == 200) {
                request.setAttribute("order", bsResult.getData());
                cartService.clearCart(request, "buyNowCart");
                //return "payment";
                return Response.createOkResp(bsResult.getData());
            } else {
                request.setAttribute("exception", bsResult.getMessage());
                //return "exception";
                return Response.createFailResp(bsResult.getMessage());
            }
        }

        //普通购物车
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        if (cart != null) {
            BSResult bsResult = orderService.createOrder(cart, userDTO, express, payMethod);

            if (bsResult.getCode() == 200) {
                request.setAttribute("order", bsResult.getData());
                cartService.clearCart(request, "cart");
                //return "payment";
                return Response.createOkResp(bsResult.getData());
            } else {
                request.setAttribute("exception", bsResult.getMessage());
                //return "exception";
                return Response.createFailResp(bsResult.getMessage());
            }

        } else {
            request.setAttribute("exception", "购物车为空！");
            //return "exception";
            return Response.createFailResp("购物车为空！");
        }

    }

    /**
     * 确认收货
     *
     * @param orderId
     * @return
     */

    @GetMapping("/confirm/{orderId}")
    @ApiOperation(value = "确认收货", notes = "确认收货")
    public ResponseResult confirmReceiving(@PathVariable("orderId") String orderId, Model model) {
        BSResult bsResult = orderService.confirmReceiving(orderId);

        if (bsResult.getCode() == 200) {
            //return "redirect:/order/list";
            return Response.createOkResp();
        } else {
            model.addAttribute("exception", bsResult.getMessage());
            //return "exception";
            return Response.createFailResp(bsResult.getMessage());
        }

    }
}
